# how to dump list into json?
# json.dumps(list)
import json  
from nekonekotrace.models import *
from nekonekotrace.logic import RenrenAPI

# functions below only return a dict struct
# not the json string

# fetch the user's information with the given user id
def userInfo(userId):
    userId = OpenUser.objects.get(id=userId)
    ud = {}
    ud['name'] = userId.Name
    ud['uid'] = userId.UID
    
    # photo send count
    ud['photonum'] = Photo.objects.filter(Author = userId).count()
    
    # favorite num
    ud['favoritecat'] = Favorite.objects.filter(UserID = userId).count()
    
    # treat times
    ud['treat'] = Treat.objects.filter(Author = userId).count()
    return ud

# fetch the user's information in www.renren.com
# must give apiClien as a parameter
def userInfoRenRen(userId, apiClient):
    target = OpenUser.objects.get(id = userId)
    
    """
        show the user Name
        Photo
        And statistics
            photo uploaded
            impression uploaded
            
            favorite pets(will get those pets news)
    """
    params = {"method": "users.getInfo", "fields": "name,headurl,tinyurl", "uids":str(target.UID)}
    response = (apiClient.request(params))
    return response
    
# return a dict
def catInfo(catInfo):
    catInfo = CatInfo.objects.get(id=catInfo)
    ret = {}
    ret['name'] = catInfo.Name
    if (catInfo.Sex == 1):
        ret['sex'] = 'male'
    else:
        ret['sex'] = 'female'
    ret['portrait'] = catInfo.Portrait
    ret['lastlocation'] = locationInfoByID(catInfo.LastLocation.id)
    ret['visits'] = catInfo.Visits
    ret['father'] = catInfo.Father
    ret['mother'] = catInfo.Mother
    
    return ret
    
    
def catInfoAll():
    ret = []
    for ci in (CatInfo.objects.all()):
        cid = catInfo(ci.id)
        ret.append(ci)
    return ret


def locationInfoByID(lInfo):
    lInfo = LocationInfo.objects.get(id=lInfo)
    ret = {}
    ret['time'] = lInfo.Time.strftime('%Y-%m-%d %H:%M:%S')
    ret['location'] = locationByID(lInfo.LocationID.id)
    ret['cat'] = lInfo.CatID
    return ret

def locationInfoByCat(catid):
    ret = []
    for lInfo in LocationInfo.objects.filter(CatID=catid).order_by("-id"):
        ret.append(locationInfoByID(lInfo.id))
    return ret

def locationInfoAll():
    ret = []
    for lInfo in LocationInfo.objects.all.order_by("-id"):
        ret.append(locationInfoByID(lInfo.id))
    return ret

#returns a array of cat impression
def catImpressionByCat(catId):
    implist = []
    catId = CatInfo.objects.get(id=catId)
    for catimp in (CatImpression.objects.all().filter(CatID=catId).order_by("-id")):
        timp = {}
        timp['id'] = catId.id
        timp['cat'] = str(catId.id)
        timp['user'] = userInfo(catimp.UserID.id)
        timp['content'] = catimp.Content
        timp['time'] = catimp.Time.strtime('%Y-%m-%d %H:%M:%S')
        implist.append(timp)
    return implist

def catImpressionByID(impId):
    implist = []
    for catimp in (CatImpression.objects.all().filter(id=impId).order_by("-id")):
        timp = {}
        timp['id'] = catimp.id
        timp['cat'] = str(catimp.CatID)
        timp['user'] = userInfo(catimp.UserID.id)
        timp['content'] = catimp.Content
        timp['time'] = catimp.Time.strtime('%Y-%m-%d %H:%M:%S')
        implist.append(timp)
    return implist

#return an array of implist
#note the the catinfo is dtailed but userinfo is just a number
def catImpressionByUser(userId):
    implist = []
    userId = OpenUser.objects.get(id=userId)
    for catimp in (CatImpression.objects.all().filter(UserID=userId).order_by("-id")):
        timp = {}
        timp['id'] = catimp.id
        timp['cat'] = catInfo(catimp.CatID.id)
        timp['user'] = str(userId.id)
        timp['content'] = catimp.Content
        timp['time'] = catimp.Time.strftime('%Y-%m-%d %H:%M:%S')
        implist.append(timp)
    return implist


#return an array of comment for a very photo
def catPhotoComment(photoId):
    photo = Photo.objects.get(id = photoId)
    pclist = []
    for pc in (PhotoComment.objects.all().filter(PhotoID=photoId)):
        pcd = {}
        pcd['id'] = pc.id
        pcd['time'] = pc.Time.strftime('%Y-%m-%d %H:%M:%S')
        pcd['content'] = pc.Content
        pcd['replyto'] = pc.ReplyTo.id
        pcd['user'] = userInfo(pc.Author.id)
        pclist.append(pcd)
    return pclist

def photoCatInclude(photoId):
    photo = Photo.objects.get(id = photoId)
    cilist = []
    for ci in (PhotoCatInclude.objects.all().filter(PhotoID = photoId)):
        cid = {}
        cid['id'] = ci.id
        cid['cat'] = catInfo(ci.CatID)
        cid['left'] = ci.Left
        cid['right'] = ci.Right
        cid['up'] = ci.Up
        cid['down'] = ci.Down
        cilist.append(cid)
    return cilist

# return a photo list of one cat
# not include the detailed info
# detailed photo can be fetched separately
def catPhotoByCat(catId):
    catId = CatInfo.objects.get(id=catId)
    phlist = []
    for catalb in (Photo.objects.all().filter(CatID=catId).order_by("-id")):
        tph = {}
        tph['id'] = catalb.id
        tph['cat'] = catInfo(catId.id)
        tph['user'] = catalb.Author.id
        tph['url'] = catalb.URL
        tph['time'] = catalb.Time.strftime('%Y-%m-%d %H:%M:%S')
        phlist.append(tph)
    return phlist
        
def catPhotoByUser(userId):
    userId = OpenUser.objects.get(id=userId)
    phlist = []
    for catalb in (Photo.objects.all().filter(Author=userId).order_by("-id")):
        phd = {}
        phd['cat'] = catInfo(catalb.CatID.id)
        phd['url'] = catalb.URL
        phd['time'] = catalb.Time.strftime('%Y-%m-%d %H:%M:%S')
        phd['user'] = userId.id
        phlist.append(phd)
    return phlist

#return a detailed information about the given photo
def catPhotoByID(phid):
    pho = Photo.objects.get(id=phid)
    ret = {}
    ret['url'] = pho.URL
    ret['location'] = locationByID(pho.Place.id)
    ret['time'] = pho.Time.Time.strftime('%Y-%m-%d %H:%M:%S')
    ret['cat'] = pho.CatID.id
    ret['user'] = pho.Author.id
    ret['title'] = pho.Title
    
    incl = []
    for inl in (PhotoCatInclude.objects.filter(PhotoID = pho.id)):
        incl.append(photoCatInclude(inl.id))
    ret['include'] = incl
    return ret
    
def catImpressionByIDGenerator(impid):
    imp = CatImpression.objects.get(id=impid)
    ret = {}
    ret['id'] = impid
    ret['cat'] = imp.CatID.id
    ret['user'] = imp.UserID.id
    ret['time'] = imp.Time.strftime('%Y-%m-%d %H:%M:%S')
    ret['content'] = imp.Content    
    return ret

def foodInfo(foodid):
    ret = {}
    for fd in Food.objects.filter(id=foodid):
        ret['name'] = fd.Name
    return ret

def catTreatAll():

    ret = []
    for catt in (Treat.objects.all().order_by("-id")):
        td = {}
        td['cat'] = catt.id
        td['user'] = catt.Author
        td['time'] = catt.Time.strftime('%Y-%m-%d %H:%M:%S')
        td['food'] = foodInfo(catt.Food) 
        ret.append(td)
    return td

def catTreatByCat(catId):
    catId = CatInfo.objects.get(id=catId)
    ret = []
    for catt in (Treat.objects.all().filter(CatID=catId).order_by("-id")):
        td = {}
        td['cat'] = catt.id
        td['user'] = catt.Author
        td['time'] = catt.Time.strftime('%Y-%m-%d %H:%M:%S')
        td['food'] = foodInfo(catt.Food) 
        ret.append(td)
    return td

def catTreatByUser(userId):
    ret = []
    for catt in (Treat.objects.all().filter(Author=userId).order_by("-id")):
        td = {}
        td['cat'] = catt.id
        td['user'] = catt.Author.id
        td['time'] = catt.Time.strftime('%Y-%m-%d %H:%M:%S')
        td['food'] = foodInfo(catt.Food) 
        ret.append(td)
    return td

def catTreatByID(Id):
    ret = []
    for catt in (Treat.objects.all().filter(id=Id).order_by("-id")):
        td = {}
        td['cat'] = catt.id
        td['user'] = catt.Author.id
        td['time'] = catt.Time.strftime('%Y-%m-%d %H:%M:%S')
        td['food'] = foodInfo(catt.Food) 
        ret.append(td)
    return td

def sayingByCat(catId):
    catId = CatInfo.objects.get(id=catId)
    ret = []
    for catalb in (Saying.objects.all().filter(CatID=catId).order_by("-id")):
        cats = {}
        cats['cat'] = catId.id
        cats['content'] = catalb.Content
        cats['time'] = catalb.Time.strftime('%Y-%m-%d %H:%M:%S')
        ret.append(cats)
    return ret


def sayingByID(Id):
    ret = []
    for catalb in (Saying.objects.all().filter(id = Id).order_by("-id")):
        cats = {}
        cats['cat'] = catalb.CatID.id
        cats['content'] = catalb.Content
        cats['time'] = catalb.Time.strftime('%Y-%m-%d %H:%M:%S')
        ret.append(cats)
    return ret

def newsByID(nId):
    nId = CatNews.objects.get(id=nId)
    ret = []
#    0 treat
#    1 photo
#    2 location
#    3 impression
#    4 saying

    if (nId.Type == 0):
        tmp = catTreatByID(nId.TargetID)
        tmp['type'] = '0'
        ret.append(tmp)
    elif (nId.Type == 1):
        tmp = catPhotoByID(nId.TargetID)
        tmp['type'] = 1
        ret.append(tmp) 
    elif (nId.Type == 2):
        tmp = locationInfoByID(nId.TargetID)
        tmp['type'] = 2
        ret.append(tmp)
    elif (nId.Type == 3):
        tmp = catImpressionByID(nId.TargetID)
        tmp['type'] = 3
        ret.append(tmp)
    elif (nId.Type == 4):
        tmp = sayingByID(nId.TargetID)
        tmp['type'] = 4
        ret.append(tmp)
    return ret

def newsSinceByCat(time, catid):
    catid = CatInfo.objects.get(id=catid)
    ret = []
    tstr = time.strftime('%Y-%m-%d %H:%M:%S')
    for cs in (CatNews.objects.filter(CatID=catid).order_by("-id")):
        if (cs.Type == 2):
            ttstr = LocationInfo.objects.get(id=cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        elif (cs.Type == 0):
            ttstr = Treat.objects.get(id=cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        elif (cs.Type == 1):
            ttstr = Photo.objects.get(id=cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        elif (cs.Type == 4):
            ttstr = Saying.objects.get(id=cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        elif (cs.Type == 3):
            ttstr = CatImpression.objects.get(id=cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        
        if(tstr <= ttstr):
            ret.append(newsByID(cs.id))
    return ret

def newsByCat(catid):
    catid = CatInfo.objects.get(id=catid)
    ret = []
    for cs in (CatNews.objects.filter(CatID=catid).order_by("-id")):
        ret.append(newsByID(cs.id))
        #jsonStr += "}"
    return ret

def newsAll():
    ret = []
    for cs in (CatNews.objects.all().order_by("-id")):
        ret.append(newsByID(cs.id))
        #jsonStr += "}"
    return ret
    


def catImpressionAllGenerator():
    count = 0
    jsonStr = "["
    for cs in (CatImpression.objects.all().order_by("-id")):
        if (count == 0):
            pass
        else:
            jsonStr += ","
        jsonStr += catImpressionByIDGenerator(cs.id)
        #jsonStr += "}"
        count += 1
    jsonStr += "]"
    return jsonStr



def newslistSinceAll(time):
    tstr = time.strftime('%Y-%m-%d %H:%M:%S')
    ret = []
    for cs in (CatNews.objects.all()):
        if (cs.Type == 2):
            ttstr = LocationInfo.objects.get(id=cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        elif (cs.Type == 0):
            ttstr = Treat.objects.get(id=cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        elif (cs.Type == 1):
            ttstr = Photo.objects.get(id=cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        elif (cs.Type == 4):
            ttstr = Saying.objects.get(id=cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        elif (cs.Type == 3):
            ttstr = CatImpression.objects.get(id=cs.TargetID).Time.strftime('%Y-%m-%d %H:%M:%S')
        if (tstr <= ttstr):
            ret.append(newsByID(cs.id))
    return ret

def locationList():
    ret = []
    for cs in (Location.objects.all()):
        ret.append(cs.id)
    return ret

def locationByID(lid):
    li = Location.objects.get(id=lid)
    ret = {}
    ret['id'] = li.id
    ret['name'] = li.Name
    ret['x'] = li.x
    ret['y'] = li.y
    return ret

## get user info by RenRenId
## must send apiClient as a param
#def userInfo(rrId, apiClient):
#    

# get a cat's follower
# given the catid, return the id of the followers 
def catfollower(catid):
    ret = [] #a new list
    for ca in Favorite.objects.filter(CatID_id=catid):
        ret.append(userInfo(ca.UserID.id))
    return json.dumps(ret)
    
    
    
    